import { Provide, Inject } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository, Not } from 'typeorm';
import { UserEntity } from '../entity/user';
import { MessageEntity } from '@/entity/message';
import { GroupEntity } from '@/entity/group';
import { GroupUserEntity } from '@/entity/groupUser';
import { GroupMsgEntity } from '@/entity/groupMsg';
import { MsgSessionEntity } from '@/entity/msgSession';

import { message, TokenUtil } from '@/util/index';

@Provide()
export class MessageService {
  @InjectEntityModel(MessageEntity)
  messageEntity: Repository<MessageEntity>;

  @InjectEntityModel(GroupEntity)
  groupEntity: Repository<GroupEntity>;

  @InjectEntityModel(GroupUserEntity)
  groupUserEntity: Repository<GroupUserEntity>;

  @InjectEntityModel(GroupMsgEntity)
  groupMsgEntity: Repository<GroupMsgEntity>;

  @InjectEntityModel(MsgSessionEntity)
  msgSessionEntity: Repository<MsgSessionEntity>;

  @InjectEntityModel(UserEntity)
  userEntity: Repository<UserEntity>;

  @Inject()
  tokenUtil: TokenUtil;

  /**
   * 获取一对一聊天消息
   */
  async getOneChatMessage(fromId: number, toId: number) {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = userToken.payload.userId;

    const msgResult = await this.messageEntity.find({
      where: [
        { fromId, toId },
        { fromId: toId, toId: fromId },
      ],
      relations: ['users'],
      order: {
        id: 'ASC',
      },
    });
    const formatData = msgResult.map(item => {
      return {
        id: item.id,
        type: item.fromId === userId ? 1 : 2,
        fromId: item.fromId,
        toId: item.toId,
        chatType: 1,
        contentType: item.contentType,
        content: item.content,
        time: item.time,
        name: item.users.username,
        imgUrl: item.users.imgUrl,
      };
    });
    return message.success(200, '获取消息', formatData);
  }

  /**
   * 获取首页消息列表
   */
  async getHomeMsgList() {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = userToken.payload.userId;
    console.log('获取首页消息列表', userId);
    const result = await this.msgSessionEntity.find({
      where: { toId: userId, unreadCount: Not(0) },
    });
    const groupResult = await this.msgSessionEntity.find({
      // where: { toId: userId, unreadCount: Not(0) },
      where: { fromId: userId, chatType: 2, unreadCount: Not(0) },
      // where: [
      //   { toId: userId, chatType: 2, unreadCount: Not(0) },
      //   { fromId: userId, chatType: 2, unreadCount: Not(0) },
      // ],
    });
    const allData = [...result, ...groupResult];
    console.log('allData', allData);
    return message.success(200, '获取首页消息列表', allData);
  }

  /**
   * 重置未读数
   */
  async resetUnread(chatType: number, fromId: number, toId: number) {
    // const userToken: any = await this.tokenUtil.verifyToken();
    // const userId = userToken.payload.userId;
    // const result = await this.msgSessionEntity.find({
    //   where: { toId: userId },
    // });
    const result = await this.msgSessionEntity
      .createQueryBuilder()
      .update()
      .set({ unreadCount: 0 })
      .where({ chatType, fromId, toId })
      .execute();
    return message.success(200, '重置未读数', result);
  }
}
